const express = require('express');
const router = express.Router();
const pool = require('../config/bd');
const { v4: uuidv4 } = require('uuid');

//创建评论
router.post('/child-comments', async (req, res) => {
  try {
    const { parent_comment_id, content, userId } = req.body;

    // 验证用户是否存在[5,8](@ref)
    const [user] = await pool.execute(
      `SELECT id, nickname, avatar FROM user WHERE id = ?`,
      [userId]
    );
    if (!user.length) {
      return res.status(404).json({ code: 404, message: '用户不存在' });
    }

    // 验证父评论是否存在
    const [parentComment] = await pool.execute(
      'SELECT id FROM comments WHERE id = ?',
      [parent_comment_id]
    );
    if (!parentComment.length) {
      return res.status(404).json({ code: 404, message: '父评论不存在' });
    }

    // 生成子评论ID
    const childCommentId = uuidv4();

    const like_count = 0

    // 执行插入（包含用户ID）
    await pool.execute(
      `INSERT INTO child_comments 
       (id, parent_comment_id, user_id, content, like_count)
       VALUES (?, ?, ?, ?, ?)`,
      [childCommentId, parent_comment_id, userId, content, like_count]
    );

    // 更新主评论子评论数[8](@ref)
    await pool.execute(
      `UPDATE comments 
       SET child_comment_count = child_comment_count + 1 
       WHERE id = ?`,
      [parent_comment_id]
    );

    // 返回带用户信息的评论数据[1,5](@ref)
    res.status(201).json({
      code: 201,
      success: true,
      data: {
        id: childCommentId,
        parent_comment_id,
        content,
        author_name: user[0].nickname,
        author_avatar: user[0].avatar,
        created_at: new Date().toISOString(),
        like_count: like_count
      },
      message: '子评论创建成功'
    });

  } catch (err) {
    console.error('创建子评论失败:', err);
    res.status(500).json({ code: 500, message: '创建失败: ' + err.message });
  }
});

//获取评论
router.get('/child-comments', async (req, res) => {
  try {
    const { parent_comment_id } = req.query;

    if (!parent_comment_id) {
      return res.status(400).json({
        code: 400,
        message: '缺少parent_comment_id参数'
      });
    }

    // 基础查询
    const [rows] = await pool.execute(
      `SELECT 
        cc.*,
        u.nickname AS author_name,
        u.avatar AS author_avatar
      FROM child_comments cc
      JOIN user u ON cc.user_id = u.id
      WHERE cc.parent_comment_id = ?
      ORDER BY cc.created_at DESC`,
      [parent_comment_id]
    );

    res.json({
      code: 200,
      success: true,
      message: '获取子评论成功！',
      data: rows[0] || null
    });

  } catch (err) {
    console.error('获取子评论失败:', err);
    res.status(500).json({
      code: 500,
      message: '获取失败: ' + err.message
    });
  }
});


module.exports = router;